"use client";

import Image from "next/image";
import { SectionHeader } from '../components/SectionHeader';
import { Card } from "../components/Card";
import { Fragment, useEffect, useState } from "react";
import { LoadingSpinner } from "@/components/ui/loading";
import { getFriends, getHomeData } from "@/lib/api";
import type { Friend, HomeData } from "@/lib/api";

export const FriendsSection = () => {
  const [friends, setFriends] = useState<Friend[]>([]);
  const [homeData, setHomeData] = useState<HomeData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const [friendsData, homeData] = await Promise.all([
          getFriends(),
          getHomeData()
        ]);
        console.log('Fetched friends data:', friendsData);
        setFriends(friendsData);
        setHomeData(homeData);
      } catch (error) {
        console.error('Error fetching friends:', error);
        setError('加载朋友列表失败，请稍后重试');
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  if (isLoading) {
    return (
      <div className="py-16 lg:py-24">
        <div className="container">
          <SectionHeader 
            eyebrow="我的朋友" 
            title="认识我的朋友们" 
            description="正在加载..." 
          />
          <div className="mt-12 lg:mt-20 flex justify-center">
            <LoadingSpinner />
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="py-16 lg:py-24">
        <div className="container">
          <SectionHeader 
            eyebrow="我的朋友" 
            title="认识我的朋友们" 
            description={error} 
          />
        </div>
      </div>
    );
  }

  if (!friends || friends.length === 0) {
    return (
      <div className="py-16 lg:py-24">
        <div className="container">
          <SectionHeader 
            eyebrow={homeData?.friend || "我的朋友"} 
            title={homeData?.friend_title || "认识我的朋友们"} 
            description="暂无朋友数据" 
          />
        </div>
      </div>
    );
  }

  const getAvatarUrl = (avatar: Friend['Avatar']) => {
    if (!avatar) return "/placeholder-avatar.jpg";
    
    if (avatar.url.startsWith('http')) {
      return avatar.url;
    } else {
      return `https://server.illli.cc${avatar.url}`;
    }
  };

  // Create a tripled array of friends for the infinite scroll effect
  const repeatedFriends = [...friends, ...friends, ...friends];

  return (
    <div className="py-16 lg:py-24">
      <div className="container">
        <SectionHeader 
          eyebrow={homeData?.friend || "我的朋友"} 
          title={homeData?.friend_title || "认识我的朋友们"} 
          description={homeData?.friend_description || "这里有一些我在技术社区认识的朋友，他们都是很棒的开发者。"} 
        />

        <div className="mt-12 lg:mt-20 flex overflow-x-clip [mask-image:linear-gradient(to_right,transparent,black_10%,black_90%,transparent)] py-4 -my-4">
          <div className="flex gap-8 pr-8 flex-none animate-move-left will-change-transform">
            {repeatedFriends.map((friend, index) => (
              <Card 
                key={`${friend.documentId}-${index}`}
                className="max-w-xs md:max-w-md md:p-8 hover:-rotate-3 transition duration-300 cursor-pointer group relative"
                onClick={() => window.open(friend.link, '_blank')}
              >
                <div className="flex gap-4 items-center">
                  <div className="size-14 bg-indigo-900 inline-flex rounded-full flex-shrink-0 items-center justify-center overflow-hidden">
                    <Image 
                      src={getAvatarUrl(friend.Avatar)}
                      alt={friend.name} 
                      width={56}
                      height={56}
                      className="w-full h-full object-cover rounded-full"
                    />
                  </div>
                  <div>
                    <div className="font-semibold">{friend.name}</div>
                    <div className="text-sm text-white/40">{friend.position}</div>
                  </div>
                </div>
                <p className="mt-4 md:mt-6 text-sm md:text-base">{friend.description}</p>
                <div className="absolute bottom-4 right-4 text-emerald-400/60 opacity-0 group-hover:opacity-100 transition-opacity">
                  点击访问 →
                </div>
              </Card>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};